package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.*;
import com.itheima.pojo.*;
import com.itheima.service.WebVisitService;
import com.itheima.utils.DateUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * @ClassName WebVisitServiceImpl
 * @Description 访问记录 服务实现类
 * @Author pengkaka
 * @Date 2020/8/4 19:27
 * @Version 1.0
 **/
@Service
public class WebVisitServiceImpl implements WebVisitService {

    @Autowired
    private WebVisitMapper webVisitMapper;

    @Autowired
    private BlogMapper blogMapper;

    @Autowired
    private BlogSortMapper blogSortMapper;

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private LinkMapper linkMapper;

    // 获取今日网站访问人数
    @Override
    public int getWebVisitCount() {
        // 获取今日开始和结束时间
        String startTime = DateUtils.getToDayStartTime();
        String endTime = DateUtils.getToDayEndTime();
        return webVisitMapper.getIpCount(startTime, endTime);
    }

    // 获取最近一周用户独立IP数和访问量
    @Override
    public Map<String, Object> getVisitByWeek() {
        // 获取到今天结束的时间
        String todayEndTime = DateUtils.getToDayEndTime();
        // 获取最近七天的日期
        Date sevenDaysDate = DateUtils.getDate(todayEndTime, -6);
        // 获取七天前的开始时间
        String sevenDaysStartTime = DateUtils.getOneDayStartTime(sevenDaysDate);
        // 获取最近七天的列表
        List<String> sevenDaysList = DateUtils.getDaysByN(7, "yyyy-MM-dd");

        // 获得最近七天的访问量
        List<Map<String, Object>> pvMap = webVisitMapper.getPVByWeek(sevenDaysStartTime, todayEndTime);
        // 获得最近七天的独立用户
        List<Map<String, Object>> uvMap = webVisitMapper.getUVByWeek(sevenDaysStartTime, todayEndTime);

        // 重新封装数据
        Map<String, Integer> countPVMap = new HashMap<>();
        Map<String, Integer> countUVMap = new HashMap<>();
        for (Map<String, Object> item : pvMap) {
            countPVMap.put(item.get("DATE").toString(), (Integer) item.get("COUNT"));
        }
        for (Map<String, Object> item : uvMap) {
            countUVMap.put(item.get("DATE").toString(), (Integer) item.get("COUNT"));
        }

        // 访问量集合
        List<Integer> pvList = new ArrayList<>();
        // 独立用户集合
        List<Integer> uvList = new ArrayList<>();

        for (String day : sevenDaysList) {
            if (countPVMap.get(day) != null) {
                Integer pvCount = countPVMap.get(day);
                pvList.add(pvCount);
            } else {
                pvList.add(0);
            }

            if (countUVMap.get(day) != null) {
                Integer uvCount = countUVMap.get(day);
                uvList.add(uvCount);
            } else {
                uvList.add(0);
            }
        }

        // 封装结果
        Map<String, Object> resultMap = new HashMap<>();

        // 不含年份的日期格式
        List<String> resultSevenDaysList = DateUtils.getDaysByN(7, "MM-dd");
        resultMap.put("date", resultSevenDaysList);
        resultMap.put("pv", pvList);
        resultMap.put("uv", uvList);

        return resultMap;
    }

    // 获取分页访问列表
    @Override
    public Page<WebVisit> getPageList(Map<String, Object> searchMap) {
        //获取分页参数
        Integer currentPage = (Integer) searchMap.get("currentPage");
        if (currentPage == null) {
            currentPage = 1;
        }
        Integer pageSize = (Integer) searchMap.get("pageSize");
        if (pageSize == null) {
            pageSize = 10;
        }
        PageHelper.startPage(currentPage, pageSize);

        Example example = new Example(WebVisit.class);
        example.setOrderByClause("create_time desc");
        Example.Criteria criteria = example.createCriteria();
        //设置关键词搜索
        if (searchMap.get("keyword") != null && !"".equals(searchMap.get("keyword"))) {
            criteria.andLike("behavior", "%" + searchMap.get("keyword") + "%");
        }
        if (searchMap.get("ip") != null && !"".equals(searchMap.get("ip"))) {
            criteria.andLike("ip", "%" + searchMap.get("ip") + "%");
        }
        // 设置起始时间
        if (searchMap.get("startTime") != null && !"".equals(searchMap.get("startTime"))) {
            String startTime = (String) searchMap.get("startTime");
            String[] time = startTime.split(",");
            if (time.length == 2) {
                criteria.andBetween("createTime", time[0], time[1]);
            }
        }

        criteria.andEqualTo("status", "1");

        List<WebVisit> webVisitList = webVisitMapper.selectByExample(example);
        
        // 设置WebVisit content属性
        // 封装相应模块对象的集合
        List<Blog> blogList = new ArrayList<>();
        List<Tag> tagList = new ArrayList<>();
        List<BlogSort> sortList = new ArrayList<>();
        List<Link> linkList = new ArrayList<>();

        for (WebVisit webVisit : webVisitList) {
            // 根据行为获取相应模块id
            // 根据模块id获取对应的模块对象,封装到对应的list
            if ("blog_content".equals(webVisit.getBehavior())) {
                String blogUid = webVisit.getModuleUid();
                Blog blog = blogMapper.selectByPrimaryKey(blogUid);
                blogList.add(blog);
            }
            if ("blog_sort".equals(webVisit.getBehavior())) {
                String sortUid = webVisit.getModuleUid();
                BlogSort blogSort = blogSortMapper.selectByPrimaryKey(sortUid);
                sortList.add(blogSort);
            }
            if ("blog_tag".equals(webVisit.getBehavior())) {
                String tagUid = webVisit.getModuleUid();
                Tag tag = tagMapper.selectByPrimaryKey(tagUid);
                tagList.add(tag);
            }
            if ("friendship_link".equals(webVisit.getBehavior())) {
                String linkUid = webVisit.getModuleUid();
                Link link = linkMapper.selectByPrimaryKey(linkUid);
                linkList.add(link);
            }
        }

        // 设置行为具体内容
        // 将集合中的数据封装到Map
        Map<String, String> contentMap = new HashMap<>();
        blogList.forEach(blog -> {
            contentMap.put(blog.getUid(), blog.getTitle());
        });
        tagList.forEach(item -> {
            contentMap.put(item.getUid(), item.getContent());
        });
        sortList.forEach(item -> {
            contentMap.put(item.getUid(), item.getContent());
        });
        linkList.forEach(item -> {
            contentMap.put(item.getUid(), item.getTitle());
        });

        webVisitList.forEach(webVisit -> {
            if ("blog_content".equals(webVisit.getBehavior()) ||
                    "blog_sort".equals(webVisit.getBehavior()) ||
                    "blog_tag".equals(webVisit.getBehavior()) ||
                    "friendship_link".equals(webVisit.getBehavior())) {
                if (StringUtils.isNotEmpty(webVisit.getModuleUid())) {
                    webVisit.setContent(contentMap.get(webVisit.getModuleUid()));
                }
            } else {
                webVisit.setContent(webVisit.getOtherData());
            }
        });
        Page<WebVisit> pageList = (Page<WebVisit>) webVisitList;
        return pageList;
    }
}
